package org.capgemini.tienda.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.capgemini.tienda.utils.RequestKeys;
import org.capgemini.tienda.utils.SessionKeys;
import org.capgemini.tienda.vo.UsuarioVO;

public class FiltroAcceso implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		final HttpSession session=((HttpServletRequest) request).getSession();
		String path=((HttpServletRequest) request).getServletPath();
		if(path.equals("/inicio.do")||path.equals("/registro.do")||path.equals("/login.do")){
			chain.doFilter(request, response);	
		}
		
			synchronized (session) {
				UsuarioVO usuario=(UsuarioVO) session.getAttribute(SessionKeys.USUARIO);
				if(usuario==null){
					request.setAttribute(RequestKeys.ERROR, "La pagina solicitada requiere login");
					RequestDispatcher rd=request.getRequestDispatcher("/inicio.do");
					rd.forward(request, response);
				} else {
					chain.doFilter(request, response);				
				}
			}
		}
//	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
	}

}
